package com.zwy.ubts.controller;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.yg.yws.annotation.YWebPath;
import com.yg.yws.annotation.YWebServlet;
import com.yg.yws.beans.RetType;
import com.zwy.ubts.bean.Address;
import com.zwy.ubts.bean.Book;
import com.zwy.ubts.bean.Order;
import com.zwy.ubts.bean.User;
import com.zwy.ubts.service.AddressService;
import com.zwy.ubts.service.BookService;
import com.zwy.ubts.service.OrderService;
import com.zwy.ubts.service.UserService;
import com.zwy.ubts.service.impl.AddressServiceImpl;
import com.zwy.ubts.service.impl.BookServiceImpl;
import com.zwy.ubts.service.impl.OrderServiceImpl;
import com.zwy.ubts.service.impl.UserServiceImpl;
import com.zwy.ubts.utils.*;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author zwy
 * @Description:
 * @Date Created in 20:03 2022/12/16
 */
@YWebServlet
public class UserController {
    private UserService service = new UserServiceImpl();
    private AddressService addressService = new AddressServiceImpl();
    private OrderService orderService = new OrderServiceImpl();
    private BookService bookService= new BookServiceImpl();


    @YWebPath("/login")
    public RetType login(){
        return RetType.retForward(DataInfo.PAGE_ROOT+"login.jsp");
    }
    @YWebPath("/doLogin")
    public RetType doLogin(String username, String password, HttpSession session){
        User login = service.login(new User(username, password));
        if (login != null){
            session.setAttribute(DataInfo.SISSON_USER,login);
            //登录成功
            return RetType.retRedirect("/");
        }else {
            //登录失败
            Map map = new HashMap();
            map.put(DataInfo.MESSAGE,DataInfo.LOGIN_ERR_FILD);
            return RetType.retForward(DataInfo.PAGE_ROOT+"login.jsp",map);
        }
    }

    @YWebPath("/register")
    public RetType register(){
        return RetType.retForward(DataInfo.PAGE_ROOT+"register.jsp");
    }

    @YWebPath("/doRegister")
    public RetType doRegister(String username, String nickname, String password,
                              String repassword,String email,String emscode,HttpSession session){
        Map map = new HashMap();
        User user = new User(username, nickname, password, email, "ys_head2.jpg");
        System.out.println(user);
        //做验证码验证
        if(service.isHaveUser(username)){
            map.put(DataInfo.MESSAGE,"账号已经存在！");
            return RetType.retForward(DataInfo.PAGE_ROOT+"register.jsp",map);
        }
        if(!password.equals(repassword)){
            map.put(DataInfo.MESSAGE,"两次密码不一致！");
            map.put("saveUser",user);
            map.put("emscode",emscode);
            return RetType.retForward(DataInfo.PAGE_ROOT+"register.jsp",map);
        }

        String key = PropertiesFile.getKey("mailcode.time");
        int time = Integer.valueOf(key);
        String mailcode = (String) session.getAttribute("mailcode");
        if (mailcode == null){
            map.put(DataInfo.MESSAGE,"请先获取验证码！");
            map.put("saveUser",user);
            return RetType.retForward(DataInfo.PAGE_ROOT+"register.jsp",map);
        }

        String[] split = mailcode.split(":");

        if (!split[2].equals(email)){
            map.put(DataInfo.MESSAGE,"两次邮箱不一样！");
            map.put("saveUser",user);
            return RetType.retForward(DataInfo.PAGE_ROOT+"register.jsp",map);
        }

        Long longTime = Long.valueOf(split[1]);
        if (longTime-System.currentTimeMillis() > time*60*1000){
            //验证码超时
            map.put(DataInfo.MESSAGE,"验证码超时。重新获取验证码！");
            map.put("saveUser",user);
            session.removeAttribute("mailcode");
            return RetType.retForward(DataInfo.PAGE_ROOT+"register.jsp",map);
        }

        if (!split[0].equals(emscode)){
            map.put(DataInfo.MESSAGE,"验证码错误！");
            map.put("saveUser",user);
            session.removeAttribute("mailcode");
            return RetType.retForward(DataInfo.PAGE_ROOT+"register.jsp",map);
        }

        //做注册
        Integer ret = service.addUser(user);
        //Integer ret = service.addUser(new User(username, nickname, new_pass, "1465865119@qq.com", "img"));
       //Integer ret = service.addUser(user);

        return RetType.retRedirect("/login");
    }

    @YWebPath("/getEMSCode")
    public RetType getEMSCode(String json,HttpSession session) throws IOException {
        System.out.println("json:"+json);
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>() {}.getType();
        Map<String, String> map = gson.fromJson(json, type);
        String toMail = map.get("toMail");
        String user = map.get("username");
        String random = RandomStringUtils.random(6);
        System.out.println(user+":"+random);
        session.setAttribute("mailcode",random+":"+ System.currentTimeMillis()+":"+toMail);

        if(service.isHaveEMail(toMail)){
            return RetType.retJson("{\"ret\":\"false\",\"data\":\"邮箱已被其他账号绑定\"}");
        }

        Mail.sendMailCode(toMail,user, random);
        return RetType.retJson("{\"ret\":\"true\",\"data\":\"\"}");
    }

    @YWebPath("/getUpdatePasswordCode")
    public RetType getUpdatePasswordCode(String email,HttpSession session){
        String random = RandomStringUtils.random(6);
        System.out.println(email +" :"+random);
        session.setAttribute(email,random);

        //通过邮箱获取用户名
        User userByEMail = service.getUserByEMail(email);
        Mail.sendMailCode(email,userByEMail.getUserName(), random);
        return RetType.retJson("{\"ret\":\"true\",\"data\":\"\"}");
    }
    //修改密码
    @YWebPath("/updatePassword")
    public RetType updatePassword(String json,HttpSession session){

        System.out.println("json:"+json);
        Gson gson = new Gson();
        Type type = new TypeToken<Map<String, String>>() {}.getType();
        Map<String, String> map = gson.fromJson(json, type);
        String email = map.get("email");
        String password = map.get("password");
        String emscode = map.get("emscode");

        if(!session.getAttribute(email).equals(emscode)){
            return RetType.retJson("{\"ret\":\"false\",\"data\":\"邮箱验证码不正确\"}");
        }
        Integer integer = service.updatePassword(email,password);
        if(integer == -1){
            return RetType.retJson("{\"ret\":\"false\",\"data\":\"邮箱未注册，请先注册\"}");
        }
        return RetType.retJson("{\"ret\":\"true\",\"data\":\"密码修改成功\"}");
    }

    //个人中心
    @YWebPath("/user")
    public RetType myUser(HttpSession session){
        User user = (User) session.getAttribute("user");

        List<Address> addressList = addressService.selectAddress(user.getUserId());
        Map addrMap = new HashMap();
        Address checkAddr = null;
        for (Address addr : addressList) {
            addrMap.put(addr.getAddrId(),addr);
            if (addr.getAddrCheck() == 1){
                checkAddr = addr;
            }
        }
        List<Book> books = bookService.selectBookByUserId(user.getUserId());
        //if (books.size() > 5){
        //    books.subList(0, books.size()-5).clear();
        //}

        ////其他人买我的书
        //List<Order> otherUserOrder = orderService.selectOrderByOtherUserId(user.getUserId());
        //if (otherUserOrder.size() > 3){
        //    otherUserOrder.subList(0, books.size()-3).clear();
        //}
        ////我买其他人的书
        //List<Order> OwnerUserOrder = orderService.selectOrderByOwnerUserId(user.getUserId());
        //if (OwnerUserOrder.size() > 3){
        //    OwnerUserOrder.subList(0, books.size()-3).clear();
        //}

        //System.out.println(new Gson().toJson(OwnerUserOrder));


        Map map = new HashMap();
        map.put("user",user);
        map.put("books",books);
        map.put("addrMap",addrMap);
        map.put("checkAddr",checkAddr);
        //map.put("otherUserOrder",otherUserOrder);
        //map.put("OwnerUserOrder",OwnerUserOrder);
        return RetType.retForward(DataInfo.PAGE_ROOT+"user.jsp",map);
    }

    //充值
    @YWebPath("/Recharge")
    public RetType Recharge(HttpSession session){
        User user = (User) session.getAttribute("user");

        Map map = new HashMap();
        map.put("user",user);

        return RetType.retForward(DataInfo.PAGE_ROOT+"recharge.jsp",map);
    }

    @YWebPath("/doRecharge")
    public RetType doRecharge(HttpSession session,String json){
        User user = (User) session.getAttribute("user");

        //更新充值
        System.out.println("json"+json);

        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(json, JsonObject.class);//将json转为JsonObject
        float amount = jsonObject.get("amount").getAsFloat();
        System.out.println("amout"+amount);

        Integer integer = service.updateUserMoneyById(user.getUserId(),amount);

        User user1 = service.selectUserById(user.getUserId());
        session.setAttribute("user",user1);
        return RetType.retJson(RetJsonUtils.toJson("充值成功！"));
    }



    //退出登录
    @YWebPath("/loginOut")
    public RetType logout(HttpServletRequest request)
    {
        request.getSession().removeAttribute("user");
        return RetType.retRedirect("/");
    }



}
